﻿using DFGJ.WMS_PDA.WebAPI.CfgFile;
using DFGJ.WMS_PDA.WebAPI.Extensions;
using DFGJ.WMS_PDA.WebAPI.Utility.Filters;
using DFGK.WMS.Common.Result;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.IRepository.IService;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using DFGK_WMS.Model.Models.PDA;
using DFGK_WMS.Repository;
using DFGK_WMS.WebAPI.AttributeFile;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.PTG;
using SqlSugar;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
using System.Security.Cryptography;
using Newtonsoft.Json;
using DFGK_WMS.Model.Helper;
using NPOI.Util;

namespace DFGJ.WMS_PDA.WebAPI.Controllers.PDA
{
    /// <summary>
    /// PDA接口 
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [ApiExplorerSettings(IgnoreApi = false, GroupName = nameof(ApiVersions.V1))]
    [AllowAnonymous]
    public class PDAHandlerController : ApiBaseController
    {

        #region Service 
        private readonly ILogger<PDAHandlerController> _Logger;

        private readonly DFGK_DB _dbContext;

        private readonly ISqlSugarClient _Client;

        //入库单明细 
        private readonly ITReceivingOrderDetailRepository _TRecevingDetail;

        //收货单
        private readonly ITReceivingBillRepository _TReceivingBill;

        //站台
        private readonly ITStationRepository _TStation;

        //入库垛  
        private readonly IStackingStorageRepository _StackingStorage;

        //倒垛
        private readonly IStackingStorageService _IStackStorageService;
        private readonly IAreaRepository areaRepository;
        private readonly ITLogRepository tLogRepository;
        private readonly ITCellRepository tcellRepository;

        #endregion



        public PDAHandlerController
            (ILogger<PDAHandlerController> logger,
             DFGK_DB dbContext,
            ITReceivingOrderDetailRepository orderDetailRepository,
            ITReceivingBillRepository tReceivingBill,
            ITStationRepository tStation,
            ISqlSugarClient client,
            IStackingStorageRepository stackingStorage,
            IStackingStorageService iStackStorageService,
            IAreaRepository areaRepository,ITLogRepository tLogRepository,
            ITCellRepository tcellRepository)
        {
            _Logger = logger;
            _dbContext = dbContext;
            _TRecevingDetail = orderDetailRepository;
            _TReceivingBill = tReceivingBill;
            _TStation = tStation;
            _Client = client;
            _StackingStorage = stackingStorage;
            _IStackStorageService = iStackStorageService;
            this.areaRepository = areaRepository;
            this.tLogRepository = tLogRepository;
            this.tcellRepository = tcellRepository;
        }


        #region 获取入库单明细数据
        /// <summary>
        /// 获取入库单明细数据
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="wareHouseId">库房Id</param>
        /// <param name="searchaString">关键字</param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetOrderListAsync/{pageIndex}/{pageSize}")]
        public async Task<IActionResult> GetOrderListAsync(int pageIndex, int pageSize, int? wareHouseId, string? searchaString = null)
        {
            try
            {

                ISugarQueryable<TReceivingOrderDetail> iQueryable = _Client.Queryable<TReceivingOrderDetail>().Where(it => it.Status >= 1 && it.Status < 4);

                iQueryable = iQueryable.WhereIF(wareHouseId != null, it => it.WarehouseId == wareHouseId);

                if (!string.IsNullOrWhiteSpace(searchaString))
                {
                    iQueryable = iQueryable.Where(t => t.OrderSn == searchaString || t.BatchNo == searchaString || t.OwnerName.Contains(searchaString) || t.MaterialCode == searchaString);
                }
                int totalCount = iQueryable.Count();
                PagingData<TReceivingOrderDetail> pagingData = new PagingData<TReceivingOrderDetail>()
                {
                    DataList = iQueryable.OrderBy(it => it.Id).ToPageList(pageIndex, pageSize),
                    RecordCount = totalCount
                };

                ApiResult<PagingData<TReceivingOrderDetail>> apiResult = new ApiResult<PagingData<TReceivingOrderDetail>>()
                {
                    Data = pagingData,
                    Success = true,
                    Code = "200"
                };
                return await Task.FromResult(new JsonResult(apiResult));

            }
            catch (Exception ex)
            {
                _Logger.LogError(ex.Message);

                return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = false, Message = ex.Message }));

            }


        }

        /// <summary>
        /// 根据订单号查询入库单
        /// </summary>
        /// <param name="OrderSn"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetReceiving")]
        public IActionResult GetReceiving(string OrderSn)
        {
            if (OrderSn is null)
            {
                return Ok(BaseResult.Result(null, "订单号不能为空", "500"));
            }
            var receivingOrder = _Client.Queryable<TReceivingOrderDetail>().Where(r => r.OrderSn == OrderSn && r.Status == 3).ToList();
            if (receivingOrder.Count > 0)
            {
                return Ok(BaseResult.Result(new
                {
                    count = receivingOrder.Count,
                    nowcount = receivingOrder.Where(r=>r.Status == 4).Count()+1,
                    data = receivingOrder.FirstOrDefault()

                }, "", "200"));
            }

            return Ok(BaseResult.Result(null, "订单已经没有数据了", "200"));
        }


        #endregion

        #region 提交入库单执行
        /// <summary>
        /// 执行入库作业
        /// </summary>
        /// <param name="orderDetailDto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("SubmitOrder")]
        [TypeFilter(typeof(IdempotentFilterAttribute))]
        public async Task<IActionResult> SubmitOrder(ReceivingOrderDetailDto orderDetailDto)
        {
            try
            {
                bool result = false;
                TReceivingOrderDetail orderDetail = _Client.Queryable<TReceivingOrderDetail>().Single(it => it.Id == orderDetailDto.Id);
                if (orderDetail == null)
                {
                    return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = false, Message = "未找到订单：" + orderDetailDto.Id }));
                }

                List<TStation> inAndOutPortStations = _Client.Queryable<TStation>().Where(it => it.StationType == 1 && it.WhId == orderDetail.WarehouseId).ToList();
                if (inAndOutPortStations == null || inAndOutPortStations.Count == 0)
                {
                    return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = false, Message = "未找到可用的出入口站台" }));

                }
                //调用外部接口
                result = true;
                if (!result)
                {
                    return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = false, Message = "调用外部服务失败" }));
                }

                string errMsg;
                result = _TRecevingDetail.ExecReceving(orderDetail, out errMsg);

                ApiBaseResult baseResult = new ApiBaseResult()
                {
                    Success = true,
                    Message = "入库执行成功"
                };
                if (!result)
                {
                    baseResult = new ApiBaseResult()
                    {
                        Success = false,
                        Message = errMsg
                    };
                }

                return await Task.FromResult(new JsonResult(baseResult));
            }
            catch (Exception ex)
            {
                _Logger.LogError(ex.Message);

                return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = false, Message = ex.Message })); throw;
            }



        }

        #endregion


        #region 收货、组垛、入库  

        /*1、获取收货单 */
        /// <summary>
        /// 获取收货单明细数据
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="warehouseid">仓库</param>
        /// <param name="searchaString"></param>
        [HttpGet]
        [Route("GettReceivingBillList/{pageIndex:int}/{pageSize:int}")]
        public async Task<JsonResult> GetReceivingBillList(int pageIndex, int pageSize, int? warehouseid)
        {
            try
            {
                //Expressionable<TReceivingBill> where = Expressionable.Create<TReceivingBill>();
                //where.And(c => c.Status < 2);
                //where.And(c => c.WarehouseId == warehouseid);

                Expression<Func<TReceivingBill, bool>> where = t => t.Status < 2 && t.WarehouseId == warehouseid;

                List<int?> billIds = _dbContext.Set<TReceivingBill>()
                    .Where(where)
                    .Select(it => it.WarehouseId)
                    .ToList();
                if (billIds == null || billIds.Count == 0)
                {
                    return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = false, Message = "暂无收货单" }));
                }
                IQueryable<TReceivingBillDetail> billDetailsQuery = _dbContext.Set<TReceivingBillDetail>()
                    .Where(it => billIds.Contains(it.BillId) && it.Status < 2)
                    .Where(it => it.Qty != it.ReceivedQty)
                    .AsQueryable();

                int count = billDetailsQuery.Count();
                List<TReceivingBillDetail> billDetails = billDetailsQuery
                     .Skip(pageIndex)
                     .Take(pageSize)
                     .OrderBy(it => it.Id)
                     .ToList();

                PagingData<TReceivingBillDetail> pagingData = new PagingData<TReceivingBillDetail>()
                {
                    DataList = billDetails,
                    RecordCount = count
                };

                ApiResult<PagingData<TReceivingBillDetail>> apiResult = new ApiResult<PagingData<TReceivingBillDetail>>()
                {
                    Code = "200",
                    Data = pagingData,
                    Success = true

                };


                return await Task.FromResult(new JsonResult(apiResult));
            }
            catch (Exception ex)
            {
                _Logger.LogError(ex.Message);

                throw new Exception(ex.Message);

            }

        }

        /*2、生成入库单  一个物料生成一个入库单*/
        /// <summary>
        /// 创建入库单
        /// </summary>
        /// <param name="orderDto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("CreateReceivingOrder")]
        [ValidateParaFilter]

        public async Task<IActionResult> CreateReceivingOrder(ReceivingOrderDto orderDto)
        {
            try
            {
                #region 参数校验
                //获取站台信息
                bool inAndOutPortStations = await _dbContext.TStations.AnyAsync(it => it.StationType == 1);
                if (!inAndOutPortStations)
                {
                    return await Task.FromResult<JsonResult>(new JsonResult(new ApiBaseResult { Success = false, Message = "未找到可用的出入口站台" }));
                }

                //获取收货单详情
                var receivingBillBillDetail = _TRecevingDetail.GetTReceivingOrderDetailById(orderDto.RecevingBillDetailId);
                if (receivingBillBillDetail is null)
                {
                    return await Task.FromResult<JsonResult>(new JsonResult(new ApiBaseResult { Success = false, Message = "收货单不存在" }));

                }
                //判断收获数量填写是否正确
                if ((receivingBillBillDetail.Qty - receivingBillBillDetail.ReceivedQty - orderDto.Qty) < 0)
                {
                    return await Task.FromResult<JsonResult>(new JsonResult(new ApiBaseResult { Success = false, Message = "收货数量填写有误" }));
                }
                #endregion

                #region 添加入库单详情

                string errMsg;
                bool result = _TRecevingDetail.AddTReceivingOrderDetail(orderDto.RecevingBillDetailId, orderDto.Qty, out errMsg);
                if (result)
                {
                    return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = true, Message = "添加成功" }));
                }
                else
                {
                    return await Task.FromResult(new JsonResult(new ApiBaseResult { Success = false, Message = errMsg }));

                }
                #endregion

            }
            catch (Exception ex)
            {
                _Logger.LogError(ex.Message);

                throw new Exception(ex.Message);
            }

        }


        /*3、PDA组垛*/
        /// <summary>
        /// PDA组垛
        /// </summary>
        /// <param name="palletBind"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("CreateStackingStorage")]
        public async Task<JsonResult> CreateStackingStorage(PalletBindMaterialDto palletBind)
        {
            try
            {
                string errMsg;

                bool result = _StackingStorage.CreateStackingStorage(palletBind, out errMsg);
                ApiBaseResult apiResult = new ApiBaseResult()
                {
                    Success = result,
                    Message = errMsg
                };
            }
            catch (Exception ex)
            {
                _Logger.LogError(ex.Message);

                ApiBaseResult apiResult = new ApiBaseResult()
                {
                    Success = false,
                    Message = "程序异常：" + ex.Message
                };
                return new JsonResult(apiResult);

            }


            return null;
        }
        #endregion

        #region  入库解绑
        /// <summary>
        /// 入库解绑
        /// </summary>
        /// <param name="unbindData">托盘条码</param>
        /// <returns></returns>
        [HttpPost]
        [Route("SubmitUnbindOfInstorage")]
        [ValidateParaFilter]

        public IActionResult SubmitUnbindOfInstorage(UnbindInstorageDto unbindData)
        {
            try
            {
                string msg;
                bool result = _StackingStorage.HandleUnbindOfInstorage(unbindData.PalletBarcode, out msg);

                ApiBaseResult apiResult = new ApiBaseResult()
                {
                    Success = result,
                    Message = msg
                };
                return new JsonResult(apiResult);
            }
            catch (Exception ex)
            {

                _Logger.LogError(ex.Message);

                ApiBaseResult apiResult = new ApiBaseResult()
                {
                    Success = false,
                    Message = "程序异常:" + ex.Message
                };
                return new JsonResult(apiResult);



            }

        }

        #endregion


        /// <summary>
        /// 消防支队PDA组垛理货
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("SubmitPalletTallyPDAData")]
        [TypeFilter(typeof(LogActionFilter))]
        public IActionResult SubmitPalletTallyPDAData(PalletTallyInputModel data)
        {
            try
            {
                if (data.OrderDetailId.GetValueOrDefault() <= 0 || string.IsNullOrEmpty(data.PalletBarcode) || data.PalletPackage == null)
                {
                    return new JsonResult(new ApiBaseResult { Code = "201", Success = false, Message = "参数错误" });
                }

                string errMsg = string.Empty;
                bool result = _IStackStorageService.BuildCreateStackingStorage(out errMsg, data);

                ApiBaseResult baseResult = new ApiBaseResult();
                if (!result)
                {
                    baseResult.Code = "500";
                    baseResult.Success = false;
                    baseResult.Message = errMsg;
                    return Ok(baseResult);
            
                }
                //result = _IStackStorageService.ExecCreateInstruct(out errMsg,);
                baseResult.Code = "200";
                baseResult.Success = true;
                baseResult.Message = "操作成功";
                return new JsonResult(baseResult);

            }
            catch (Exception)
            {

                throw;
            }


        }


        /// <summary>
        /// 入库
        /// </summary>
        /// <param name="PalletCode">托盘码</param>
        /// <returns></returns>
        [HttpPost]
        [Route("ExecCreateInventory")]
        [TypeFilter(typeof(LogActionFilter))] //用于日志使用的特性
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult ExecCreateInventory(string PalletCode)
        {
            var stackingStorage = _Client.Queryable<TStackingStorage>().First(s=>s.Status == 1 && s.PalletBarcode == PalletCode);
            ApiBaseResult baseResult = new ApiBaseResult();
            if (stackingStorage is null)
            {
                baseResult.Code = "500";
                baseResult.Success = false;
                baseResult.Message = "无组垛信息";
                return Ok(baseResult);
            }
            var orderDetail = _Client.Queryable<TReceivingOrderDetail>().First(x => x.Id == stackingStorage.RelatedOrderDetailId);
            //TStation station = _Client.Queryable<TStation>().First(r => r.WhId == orderDetail.WarehouseId);
            DFGK_WMS.Model.Models.PalletBindMaterialModel palletBindMaterialModel = new DFGK_WMS.Model.Models.PalletBindMaterialModel()
            {
                PalletBarcode = PalletCode,
                MaterialPackageBindModel = new DFGK_WMS.Model.Models.MaterialPackageBindModel()
                {
                    OrderDetailId = orderDetail.Id,
                    MaterialCode = orderDetail.MaterialCode,
                    Qty = orderDetail.Qty,
                }
            };
            string errMsg = string.Empty;
            var result = _IStackStorageService.ExecCreateInstruct(out errMsg, orderDetail, palletBindMaterialModel);
           
            if (!result)
            {
                baseResult.Code = "500";
                baseResult.Success = false;
                baseResult.Message = errMsg;
                return Ok(baseResult);
            }
            baseResult.Code = "200";
            baseResult.Success = true;
            baseResult.Message = "操作成功";
            return new JsonResult(baseResult);
        }

        /// <summary>
        /// 入库(多个物料的) （海宁的）
        /// </summary>
        /// <param name="Palletlist">托盘码</param>
        /// <returns></returns>
        [HttpPost]
        [Route("ExecCreateMaterialsInventory")]
        [TypeFilter(typeof(LogActionFilter))] //用于日志使用的特性
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult ExecCreateMaterialsInventory(string PalletCode)
        {
            string errMsg = string.Empty;
            List<string> invenlist = new List<string>();
            try
            {
                
                var stackingStorages = _Client.Queryable<TStackingStorage>().Where(s => s.Status == 1 && s.PalletBarcode == PalletCode).ToList();
                ApiBaseResult baseResult = new ApiBaseResult();
                if (stackingStorages is null || stackingStorages.Count() <= 0)
                {
                    baseResult.Code = "500";
                    baseResult.Success = false;
                    baseResult.Message = "无组垛信息";
                    return Ok(baseResult);
                }

                var checkin = _IStackStorageService.ExecCreateMaterials(out errMsg, stackingStorages);
                tLogRepository.Add(new TLog()
                {
                    LogType = 1,
                    ActionType = 0,
                    Description = checkin == true ? "入库（多个物料的）：入库成功！" : "入库（多个物料的）：" + errMsg,
                    CreateDate = DateTime.Now
                });
                if (checkin)
                {
                    _Client.Ado.CommitTran();
                    baseResult.Code = "200";
                    baseResult.Success = true;
                    baseResult.Message = "入库成功";
                    return new JsonResult(baseResult);
                }
                return Ok(BaseResult.Result(false, errMsg, "200"));
            }
            catch (Exception)
            {
                tLogRepository.Add(new TLog()
                {
                    LogType = 1,
                    ActionType = 0,
                    Description = errMsg,
                    CreateDate = DateTime.Now
                });
                throw;
            }
        }

        /// <summary>
        /// 入库(没有网络)
        /// </summary>
        /// <param name="Palletlist">托盘码</param>
        /// <returns></returns>
        [HttpPost]
        [Route("ExecCreateInventoryNoNet")]
        [TypeFilter(typeof(LogActionFilter))] //用于日志使用的特性
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult ExecCreateInventoryNoNet(List<string> Palletlist)
        {
            bool checkin = true;
            string errMsg = string.Empty;
            List<string> invenlist = new List<string>();
            try
            {
                foreach (var PalletCode in Palletlist)
                {
                    var stackingStorage = _Client.Queryable<TStackingStorage>().First(s => s.Status == 1 && s.PalletBarcode == PalletCode);
                    ApiBaseResult baseResult = new ApiBaseResult();
                    if (stackingStorage is null)
                    {
                        baseResult.Code = "500";
                        baseResult.Success = false;
                        baseResult.Message = "无组垛信息";
                        return Ok(baseResult);
                    }
                    var orderDetail = _Client.Queryable<TReceivingOrderDetail>().First(x => x.Id == stackingStorage.RelatedOrderDetailId);
                    //TStation station = _Client.Queryable<TStation>().First(r => r.WhId == orderDetail.WarehouseId);
                    DFGK_WMS.Model.Models.PalletBindMaterialModel palletBindMaterialModel = new DFGK_WMS.Model.Models.PalletBindMaterialModel()
                    {
                        PalletBarcode = PalletCode,
                        MaterialPackageBindModel = new DFGK_WMS.Model.Models.MaterialPackageBindModel()
                        {
                            OrderDetailId = orderDetail.Id,
                            MaterialCode = orderDetail.MaterialCode,
                            Qty = orderDetail.Qty,
                        }
                    };
                    var result = _IStackStorageService.ExecCreateInstruct(out errMsg, orderDetail, palletBindMaterialModel);
                    if (result == false)
                    {
                        checkin = result;
                        invenlist.Add("失败托盘编码：" + PalletCode + "错误信息：" + errMsg);
                    }
                }
                if (checkin)
                {
                    ApiBaseResult baseResult = new ApiBaseResult();
                    baseResult.Code = "200";
                    baseResult.Success = true;
                    baseResult.Message = "入库成功";
                    return new JsonResult(baseResult);
                }
                errMsg = string.Join(", ", invenlist);
                return Ok(BaseResult.Result(false, errMsg, "200"));
            }
            catch (Exception)
            {
                tLogRepository.Add(new TLog()
                {
                    LogType = 1,
                    ActionType = 0,
                    Description = errMsg,
                    CreateDate = DateTime.Now
                });
                throw;
            }
        }

        /// <summary>
        /// 查询入库单
        /// </summary>
        /// <param name="PalletCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetReceivingBill")]
        public IActionResult GetReceivingBill(string PalletCode)
        {
            var stackingStorages = _Client.Queryable<TStackingStorage>().Where(s => s.Status == 1 && s.PalletBarcode == PalletCode).ToList();
            List<OrderDetailDataDTO> orderdata = new List<OrderDetailDataDTO>();
            foreach (var stackingStorage in stackingStorages)
            {
                var orderDetail = _Client.Queryable<TReceivingOrderDetail>().First(x => x.Id == stackingStorage.RelatedOrderDetailId);
                if (orderDetail is null)
                {
                    return Ok(BaseResult.Result(null, "入库单查询失败", "200"));
                }
                orderdata.Add(new OrderDetailDataDTO()
                {
                    OrderDetailId = orderDetail.Id,
                    PallteCode = stackingStorage.PalletBarcode,
                    cell = stackingStorage.ExpectedLocation,
                    OrderNo = orderDetail.OrderSn,
                    MaterialCode = orderDetail.MaterialCode,
                    Num = orderDetail.StackedQty,
                });
            }
            return Ok(BaseResult.Result(orderdata, "成功", "200"));
        }

        /// <summary>
        /// 判断托盘是否可用
        /// </summary>
        /// <param name="PallCode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("PalletVerify")]
        [NonAction]
        public IActionResult PalletVerify(string PalletCode)
        {
            ApiBaseResult baseResult = new ApiBaseResult();
            TStackingStorage storageModel = _Client.Queryable<TStackingStorage>().First(r => r.Status == 1 && r.PalletBarcode == PalletCode);
            if (storageModel != null)
            {
                baseResult.Code = "200";
                baseResult.Success = false;
                baseResult.Message = "托盘已在组垛中";
                return Ok(baseResult);
            }
            var inventory = _Client.Queryable<TInventory>().First(r=>r.PalletBarcode == PalletCode);
            if (inventory is not null)
            {
                baseResult.Code = "200";
                baseResult.Success = false;
                baseResult.Message = "当前托盘已在库存中";
                return Ok(baseResult);
            }
            
            baseResult.Code = "200";
            baseResult.Success = true;
            baseResult.Message = "";
            return new JsonResult(baseResult);
        }

        /// <summary>
        /// 查询全部收货单(分页)
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetReceivingBillList")]
        public IActionResult GetReceivingBillList(int isNetWork, int supplierId = 0, int status = 3, int warehouseId = 0, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;

            var list = _TReceivingBill.GetReceivingBillList(supplierId, status, warehouseId, pageIndex, pageSize, out totalCount).Where(r=>r.Status == 0 || r.Status == 1);
            //if (isNetWork == 0)
            //{
            //    list = list.Where(r => r.Status == 0 || (r.AreaCode == "A04" && r.Status == 1));
            //}
            //if (isNetWork == 1)
            //{
            //    list = list.Where(r => r.Status == 0 || (r.AreaCode != "A04" && r.Status == 1));
            //}
            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", 0));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 查询全部收获单RFID
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetListReceiving")]
        public IActionResult GetListReceiving()
        {
            var list = _TReceivingBill.GetListRedceiving();

            if (list != null)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", list.Count));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        /// <summary>
        /// 修改收货单状态（已提交 海宁）
        /// </summary>
        /// <param name="checkNumber"></param>
        /// <param name="orderIds"></param>
        /// <returns></returns>
        [HttpPut]
        [Route("UpdateReceivingBillStatus")]
        [TypeFilter(typeof(LogActionFilter))] //用于日志使用的特性
        public IActionResult UpdateReceivingBillStatus(string checkNumber,string orderIds)
        {
            var res = _Client.Queryable<TReceivingBill>().First(r => r.BillNo == checkNumber);
            if (res is null)
            {
                return Ok(BaseResult.Result(null, "未找到验收单！", "500"));
            }
            var rids = orderIds.Split(',');
            _Client.Ado.BeginTran();
            try
            {
                foreach (var rid in rids)
                {
                    var rdata = _Client.Queryable<TReceivingOrderDetail>().First(r => r.Id == Convert.ToInt32(rid));
                    if (rdata is null)
                    {
                        _Client.Ado.RollbackTran();
                        tLogRepository.Add(new TLog()
                        {
                            LogType = 1,
                            ActionType = 0,
                            Description = "未查出入库单! 单号：" + checkNumber,
                            CreateDate = DateTime.Now
                        });
                        return Ok(BaseResult.Result(null, "未查出入库单！", "500"));
                    }
                    rdata.Status = 9;
                    if (_Client.Updateable<TReceivingOrderDetail>(rdata).ExecuteCommand() <= 0)
                    {
                        _Client.Ado.RollbackTran();
                        tLogRepository.Add(new TLog()
                        {
                            LogType = 1,
                            ActionType = 0,
                            Description = "修改入库单失败! 单号：" + checkNumber,
                            CreateDate = DateTime.Now
                        });
                        return Ok(BaseResult.Result(null, "修改入库单失败！", "500"));
                    };
                }
                var receorder = _Client.Queryable<TReceivingOrderDetail>().Where(r => r.ReceivingBillId == res.Id && r.Status != 9).ToList();
                if (receorder is null || receorder.Count() <= 0 && res.Status == 2)
                {
                    res.Status = 3;
                    var isOk = _Client.Updateable<TReceivingBill>(res).ExecuteCommand();
                    if (isOk <= 0)
                    {
                        _Client.Ado.RollbackTran();
                        tLogRepository.Add(new TLog()
                        {
                            LogType = 1,
                            ActionType = 0,
                            Description = "修改收货单失败! 单号：" + checkNumber,
                            CreateDate = DateTime.Now
                        });
                        return Ok(BaseResult.Result(null, "修改收货单失败！", "500"));
                    }
                }
                _Client.Ado.CommitTran();
                tLogRepository.Add(new TLog()
                {
                    LogType = 1,
                    ActionType = 0,
                    Description = "修改状态成功! 单号：" + checkNumber,
                    CreateDate = DateTime.Now
                });
                return Ok(BaseResult.Result(null, "修改状态成功！", "200"));
               
            }
            catch (Exception)
            {
                _Client.Ado.RollbackTran();
                tLogRepository.Add(new TLog()
                {
                    LogType = 1,
                    ActionType = 0,
                    Description = "修改收货单失败! 单号：" + checkNumber,
                    CreateDate = DateTime.Now
                });
                return Ok(BaseResult.Result(null, "修改收货单失败！", "500"));
                throw;
            }
        }

        /// <summary>
        /// 查询收货单的商品 （海宁）
        /// </summary>
        /// <param name="receivingBillId"></param>
        /// <param name="materialCode"></param>
        /// <param name="articlebarcode"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("GetReceivingBillGoodsDeatil")]
        public IActionResult GetReceivingBillGoodsDeatil(int receivingBillId,string? materialCodeArticlebarcode)
        {
            ApiBaseResult baseResult = new ApiBaseResult();
            if (receivingBillId <= 0 || materialCodeArticlebarcode is null)
            {
                baseResult.Code = "500";
                baseResult.Success = false;
                baseResult.Message = "参数有误";
                return Ok(baseResult);
            }
          
            var recevingbilldeta = _Client.Queryable<TReceivingBillDetail>().First(r => r.BillId == receivingBillId && r.MaterialCode == materialCodeArticlebarcode);

            if (recevingbilldeta is null)
            {
                baseResult.Code = "500";
                baseResult.Success = false;
                baseResult.Message = "未查出物料";
                return Ok(baseResult);
            }
            return Ok(BaseResult.Result(recevingbilldeta, "查询成功", "200"));
        }

        /// <summary>
        /// 查询是否存在这个仓位（海宁 目前不用）
        /// </summary>
        /// <param name="storeLocationCode"></param>                                                                                                                                   
        /// <returns></returns>
        [HttpGet]
        [Route("Getlocation")]
        [NonAction]
        public async Task<IActionResult> Getlocation(string storeLocationCode)
        {
            var token = await HttpHelper.GetToken("");
            using var client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", token);
            // 发送GET请求
            HttpResponseMessage response = await client.GetAsync("/railway/v1/pda/store/location/list");
            // 检查请求是否成功
            if (response.IsSuccessStatusCode)
            {
                var res = await response.Content.ReadAsStringAsync();

                var responseObject = System.Text.Json.JsonSerializer.Deserialize<LocationListDTO>(res);

                if (responseObject is null)
                {
                    return Ok(BaseResult.Result(null, "查询失败", "500"));
                }

                var data = responseObject.data.Where(s => s.storeLocationCode == storeLocationCode).FirstOrDefault();

                if (data is null)
                {
                    return Ok(BaseResult.Result(null, "查询失败", "500"));
                }

                return Ok(BaseResult.Result(data, "查询成功", "200"));
            }
            else
            {
                return Ok(BaseResult.Result(null, "请求失败", "500"));
            }
        }

        /// <summary>
        /// 查询全部库区
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetAreaList")]
        [NonAction]
        public IActionResult GetAreaList()
        {
            var list = areaRepository.GetAll().ToList();
            if (list.Count() <= 0)
            {
                return Ok(BaseResult.Result(null, "查询失败", "500"));
            }
            return Ok(BaseResult.Result(list, "查询成功", "200"));
        }

        /// <summary>
        /// 获取提交入库的数据(海宁)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetCheck")]
        public IActionResult GetCheck()
        {
            var list = _TReceivingBill.GetSubmitOutList().FirstOrDefault();
            if (list is null)
            {
                return Ok(BaseResult.Result(null, "没有到数据", "200"));
            }
            return Ok(BaseResult.Result(list, "查询成功", "200"));
        }

        /// <summary>
        /// PDA收货入库
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("BuildCreateStackingStorage")]
        [TypeFilter(typeof(LogActionFilter))]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult BuildCreateStackingStorage(ReceivingBillOrderDto m)
        {
            if (m.Id <= 0)
            {
                return Ok(BaseResult.Result("400", "Id有误！"));
            }
            m.NowUserId = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
            m.NowUserRealName = HttpContext.User.FindFirstValue("UserName");
            string message = "";
            bool IsOK = _TReceivingBill.AddPDAReceivingOrderDateil(m, out message);
            if (IsOK)
            {
                return Ok(BaseResult.Result(true, "保存成功！", "200"));
            }
            return Ok(BaseResult.Result(false, message, "500"));
        }

        /// <summary>
        /// PDA收货入库(无网)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("BuildCreateStackingStorageNoNet")]
        [TypeFilter(typeof(LogActionFilter))]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult BuildCreateStackingStorageNoNet(List<ReceivingBillOrderDto> list)
        {
            bool checkin = true;
            List<string> receivingNo = new List<string>();
            string message = "";
            try
            {
                foreach (var m in list)
                {
                    m.NowUserId = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                    m.NowUserRealName = HttpContext.User.FindFirstValue("UserName");
                    
                    bool IsOK = _TReceivingBill.AddPDAReceivingOrderDateilNoNet(m, out message);
                    checkin = IsOK;
                    if (!checkin)
                    {
                        receivingNo.Add("单号" + m.OrderNo + "错误信息" + message);
                    }
                }
                if (checkin)
                {
                    return Ok(BaseResult.Result(true, "保存成功！", "200"));
                }
                message = string.Join(", ", receivingNo);
                return Ok(BaseResult.Result(false, message, "200"));
            }
            catch (Exception)
            {
                tLogRepository.Add(new TLog()
                {
                    LogType = 1,
                    ActionType = 0,
                    Description = message,
                    CreateDate = DateTime.Now
                });
                throw;
            }
            

        }

        /// <summary>
        /// PDA收货入库(可以组多个物料 海宁)
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("BuildCreateStackingStorageMaterials")]
        [TypeFilter(typeof(LogActionFilter))]
        [HttpIdempotent(WaitMillisecond = 10000, CacheMillisecond = 3000)]
        public IActionResult BuildCreateStackingStorageMaterials(ReceivingBillOrderMaterialsDto m)
        {
            string message = "";
            try
            {
                if (m.Id <= 0)
                {
                    return Ok(BaseResult.Result("400", "Id有误！"));
                }
                m.NowUserId = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                m.NowUserRealName = HttpContext.User.FindFirstValue("UserName");

                bool IsOK = _TReceivingBill.BuildCreateStackingStorageMaterials(m, out message);
                tLogRepository.Add(new TLog()
                {
                    LogType = 1,
                    ActionType = 0,
                    Description = IsOK == true ? "组垛：组垛成功" : "组垛：" + message,
                    CreateDate = DateTime.Now
                });
                if (IsOK)
                {
                    return Ok(BaseResult.Result(true, "保存成功！", "200"));
                }
                return Ok(BaseResult.Result(false, message, "500"));
            }
            catch (Exception)
            {
                tLogRepository.Add(new TLog()
                {
                    LogType = 1,
                    ActionType = 0,
                    Description = message,
                    CreateDate = DateTime.Now
                });
                throw;
            }
        }


        /// <summary>
        /// 查询全部仓位的仓位 海宁
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="cellName"></param>
        /// <param name="pageIndex"></param>
        /// <param name="areascode"></param>
        /// <returns></returns>
        [HttpGet,Route("GetCellListByCellName")]
        public IActionResult GetCellListByCellName(string? cellName, int pageSize = 10,int pageIndex = 1)
        {
            var cellList = tcellRepository.GetAll().Where(s=>s.Status == 1 && s.IsLock == false && s.FullStatus == 0 && s.WhId == 70).ToList();
            if (!string.IsNullOrEmpty(cellName))
            {
                cellList = cellList.Where(s => s.Name.Contains(cellName)).ToList();
            }
            //if (!string.IsNullOrEmpty(areascode))
            //{
            //    cellList = cellList.Where(s => s.AreaCode == areascode).ToList();
            //}
            var resCellList = cellList.Skip((pageIndex - 1) * pageSize).Take(pageSize).Select(s => new {
                s.Name,
                s.Code,
                s.WhId,
                s.Erpcode, //==仓位id
            });
            return Ok(BaseResult.Result(resCellList, "请求成功", "200",resCellList.Count()));
        }

    }
}
